package homework;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: knowno
 * @create: 2025-09-17 09:08
 * @Version 1.0
 **/
public class UserDao {

    List<User> list = new ArrayList<>();

    /**
     * 保存用户
     *
     * @param user 一个User对象
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public boolean save(User user) throws IOException, ClassNotFoundException {

        //1 =>ObjectOutputStream 对象

        //public ObjectOutputStream(OutputStream out)  =>抽象类
        //class FileOutputStream extends OutputStream
        //public FileOutputStream(String name, boolean append)
        OutputStream outputStream = new FileOutputStream("d:\\demo\\user.ini");

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

        //读取当前存在的用户记录:
        read();

        //将user添加到集合list,以list为单位进行序列化操作
        list.add(user);

        //2保存,序列化操作
        objectOutputStream.writeObject(list);

        //3 释放资源
        outputStream.close();
        objectOutputStream.close();

        return true;
    }

    /**
     * 读取文件
     *
     * @return List<User>
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public List<User> read() {

        File file = new File("d:\\demo\\user.ini");

        InputStream inputStream = null;
        ObjectInputStream objectInputStream = null;
        List<User> readList = null;
        try {

            if (!file.exists()) {
                file.createNewFile();
            }
            //1 创建ObjectInputStream
            inputStream = new FileInputStream("d:\\demo\\user.ini");

            objectInputStream = new ObjectInputStream(inputStream);

            //2 读到的数据存储到List中来
            readList = (List<User>) objectInputStream.readObject();

            //3 释放资源
            inputStream.close();
            objectInputStream.close();

        } catch (IOException exception) {
            return null;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }


        return readList;

    }


}
